#include <exception>
#include <stdexcept>
#include "Mutex.h"

DEF_BEG_LIBTOOLS

#define THROW_MUTEX throw std::invalid_argument("mutex is NULL")

CMutex::CMutex()
{
	 _mutex = ShareApi::CreateMutex();
}

CMutex::~CMutex()
{
	if (_mutex)
	{
		ShareApi::CloseMutex(_mutex);
		 _mutex = 0;
	}
}

void CMutex::Lock()
{
	if (!_mutex) THROW_MUTEX;
	ShareApi::MutexLock(_mutex);
}

void CMutex::Unlock()
{
	if (!_mutex) THROW_MUTEX;
	ShareApi::MutexUnlock(_mutex);
}

SYNCHANDLE CMutex::Handle()
{
	return _mutex;
}

CLockGurad::CLockGurad(CMutexBase *pBase)
{
	 _mutex = pBase;
	Lock();
}


CLockGurad::~CLockGurad()
{
	Unlock();
}

void CLockGurad::Lock()
{
	 _mutex->Lock();
}

void CLockGurad::Unlock()
{
	 _mutex->Unlock();
}

DEF_END_LIBTOOLS